import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/presenter/review_presenter.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/review_details_ui.dart';

import '../../../../../http/bean/http_data.dart';
import '../../../../../http/bean/worksdo/equipment_management_bean.dart';
import '../../../../../http/bean/worksdo/hardware_collar_bean.dart';
import '../../../../../http/model/equipment_management_model.dart';
import '../../../../dialog/dailog.dart';
import '../../../helper/route_helper.dart';
import 'ui/review_submitted.dart';
import 'ui/ui_form.dart';

///我的工单；工单领用（五金领用）
class ReceiptofworkorderRoute extends StatefulWidget {
  @override
  _State createState() => _State();

  EquipmentInfo? data;

  ReceiptofworkorderRoute(this.data);
}

class _State extends State<ReceiptofworkorderRoute> {
  _Presenter presenter = _Presenter();

  @override
  void initState() {
    super.initState();
    if (presenter?.mDatas == null) {
      presenter?.mDatas = AppHttpResult<String, String>();
    }

    ///fixme 现在物料请购所有数据都是从上一个页面带过来的。
    presenter?.data = widget.data;

    // ///延迟获取数据
    // presenter.GetRepairPersonListWithDelay(context, callback: () {});
  }

  @override
  Widget build(BuildContext context) {
    return ReviewDetailsUi.build(context, presenter, _body,
        title: AppStrings.of(context).Myworkorder +
            ":" +
            AppStrings.of(context).Hardwarecollar); //我的工单:五金领用
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    UiForm1.clear(); //数据缓存清除
  }

  bool isQuest = false; //页面首次进入，不主动请求。数据太大了。卡。

  Widget _body(BuildContext context) {
    var mDatas = widget.data;
    if (mDatas == null) {
      return AppUi.getEmptyView();
    }
    List<Widget> children = [];
    children.add(UiForm1.build(context, presenter?.getEquipmentResponseData(),
        isQuest, presenter?.setStateBody, callbackWithVoid: () {
      //五金搜索条件回调
    })); //五金领用列表
    if (isQuest) {
      isQuest = false;
    }
    return Column(
      children: [
        Expanded(child: UiBase.listView(context, children)),
        Visibility(
            child:
                ReviewSubmittedStateful3(presenter?.getEquipmentResponseData(),
                    callbackWithT: (subData) {
              //fixme 提交参数数据
            }, callbackWithBoolResult: () {
              //fixme 提交数据格式验证
              var data = presenter?.getEquipmentResponseData();
              var hardwareDatas = data?.hardwareDatas; //五金数据。
              try {
                if (StringUtils.isEmpty(hardwareDatas)) {
                  AppDialog.showDialogWithInfo(context,
                      content: AppStrings.of(context).nosubmitdata); //没有可提交的数据
                  return false;
                } else {
                  List<HardwareBean>? hardwareDatas2 = [];
                  hardwareDatas?.forEach((element) {
                    var sumBasicNum2 = element.getsumBasicNum2();
                    // print("领用数量：${sumBasicNum2}");
                    if (sumBasicNum2 > 0) {
                      hardwareDatas2?.add(element); //帅选领用数量大于0的五金。
                    }
                  });
                  // print("领用数据条目：${hardwareDatas2.length}");
                  if (hardwareDatas2 == null || hardwareDatas2.length <= 0) {
                    AppDialog.showDialogWithInfo(context,
                        content: AppStrings.of(context)
                            .wujinlingyshulian); //请填写你所需领五金的领用数量
                    return false;
                  }
                  if (data?.submitHardwareReceive == null) {
                    data?.submitHardwareReceive = SubmitHardwareReceive();
                  }
                  data?.submitHardwareReceive?.ItemInfo =
                      hardwareDatas2; //五金领用数据
                }
              } catch (e) {}
              return true;
            }, responseCallbackWithBool: (value) {
              //fixme 提交返回结果
              if (value) {
                presenter?.setStateBody?.call(() {
                  ///刷新整个页面
                  isQuest = true;
                });
              }
            }),
            visible: presenter?.data != null)
      ],
    );
  }
}

class _Presenter extends ReviewPresenter {
  //工单信息
  EquipmentInfo? data = null;

  //报修人员
  List<MaintenanceManInfo>? maintenanceManInfos = null;

  //提交数据
  EquipmentResponseData? _equipmentResponseData = null;

  EquipmentResponseData getEquipmentResponseData() {
    if (_equipmentResponseData == null) {
      _equipmentResponseData = EquipmentResponseData();
    }
    _equipmentResponseData?.equipmentInfo = data;
    _equipmentResponseData?.maintenanceManInfos = maintenanceManInfos;
    return _equipmentResponseData!;
  }

  ///获取审核详情数据
  GetRepairPersonList(BuildContext context,
      {ResponseCallbackWithVoid? callback = null}) {
    isLoad = true;
    //报修人员
    EquipmentManagementModel.GetRepairPersonList(context, true,
        onError: (code, error) {
      isLoad = false;
      setStateBody?.call(() {});
      AppDialog.showDialogWithError(context, code, error)?.then((value) {
        AppRouteHelper.pop(context); //网络异常，关闭当前页面
      });
    })?.then((value) {
      isLoad = false;
      if (value.isSuccessForCode()) {
        try {
          maintenanceManInfos = value?.Data;
          setStateBody?.call(() {});
          callback?.call();
        } catch (e) {}
      } else {
        //异常
        AppDialog.showDialogWithInfo(context, content: value.MsgDetail)
            ?.then((value) {
          AppRouteHelper.pop(context); //关闭当前页面
        });
      }
    });
  }

  ///获取审核详情数据[延迟获取，等待页面加载完成]
  GetRepairPersonListWithDelay(BuildContext context,
      {ResponseCallbackWithVoid? callback = null}) {
    Future.delayed(Duration(milliseconds: 200)).then((e) {
      GetRepairPersonList(context, callback: callback);
    });
  }
}
